package com.walter.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author Walter
 * @date 2025/2/5 下午5:12
 **/
@Component
@Slf4j
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }

        // 设置 Content-Type 为 JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBufferFactory bufferFactory = response.bufferFactory();

        HttpStatus status = determineHttpStatus(ex);
        response.setStatusCode(status);

        String errorMessage = determineErrorMessage(ex);
        CommonResult<Void> errorResult = CommonResult.error(status.value(), errorMessage); // 使用错误状态码和消息

        byte[] errorBytes;
        try {
            errorBytes = objectMapper.writeValueAsBytes(errorResult);
        } catch (JsonProcessingException e) {
            log.error("Error serializing error response to JSON", e);
            errorBytes = "{\"code\":500,\"message\":\"Internal Server Error\"}".getBytes(StandardCharsets.UTF_8); // 备用错误 JSON
        }

        return response.writeWith(Mono.just(bufferFactory.wrap(errorBytes)));
    }

    private HttpStatus determineHttpStatus(Throwable ex) {
//        if (ex instanceof ResponseStatusException) {
//            return ((ResponseStatusException) ex).getStatus();
//        }
        // 可以根据异常类型细化状态码，这里作为示例统一返回 500
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }

    private String determineErrorMessage(Throwable ex) {
        if (ex instanceof ResponseStatusException) {
            return ex.getMessage(); // 直接使用 ResponseStatusException 中的 message
        }
        // 可以根据异常类型提供更友好的错误消息，这里作为示例统一返回 "Internal Server Error"
        return "Internal Server Error";
    }
}
